
package com.sun.showcase.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sun.showcase.annotation.LoginAuth;
import com.sun.showcase.exception.InvalidTokenException;
import com.sun.showcase.utils.JwtUtils;
import com.sun.showcase.utils.LoginContext;
import com.sun.showcase.utils.LoginContextHolder;

import io.jsonwebtoken.Claims;

/**
 * 权限(Jwt)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;
    
    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	LoginAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(LoginAuth.class);
         }else{
            return true;
        }

        if(annotation == null){
            return true;
        }
        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new InvalidTokenException();
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims != null && jwtUtils.isAdvanceExpired(claims.getExpiration())){
    		response.addHeader("newToken", jwtUtils.generateToken(Long.parseLong(claims.getSubject())));
    	}
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
        		throw new InvalidTokenException();
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));
        LoginContext loginContext = new LoginContext();
        loginContext.setUserId(claims.getSubject());
        LoginContextHolder.put(loginContext);
        return true;
    }
    
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		LoginContextHolder.clear();//本次访问结束，清除信息。
	}
}
